package com.spica.platform.base.resolver;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 分页、查询参数解析
 */
public class PageArgumentResolver implements HandlerMethodArgumentResolver {

	
	private static final String START = "page" ;
	private static final String LENGTH = "limit" ;
	
	@Override
	public boolean supportsParameter(MethodParameter parameter) {
		Class<?> cla = parameter.getParameterType();

		return cla.isAssignableFrom(Page.class);
	}

	@Override
	public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
			NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
		HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);

		Page tableRequest = new Page();
		Map<String, String[]> param = request.getParameterMap();
		if (param.containsKey(START)) {
			tableRequest.setCurrent(Integer.parseInt(request.getParameter(START)));
		}

		if (param.containsKey(LENGTH)) {
			tableRequest.setSize(Integer.parseInt(request.getParameter(LENGTH)));
		}
		return tableRequest;
	}
}
